package DAO;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.stereotype.Repository;

import POJO.Company;

@Repository
public class CompanyDao {
	@Autowired
	JdbcTemplate jdbcTemplate;
	/**
	 * 返回指定公司名根据ID
	 * @param id
	 * @return
	 */
	public String getCompanyNameById(int id){
		String getCompanyNameByIdSql="SELECT company_name FROM company where company_id=?;";
		Object[] params=new Object[]{id};
		String company=null;
		try {
			company=jdbcTemplate.queryForObject(getCompanyNameByIdSql, params,String.class);
		} catch (Exception e) {
		}
		return company;
	}
	
	/**
	 *返回所有快递公司
	 * @return
	 */
	public ArrayList<Company> getAllCompanys(){
		final ArrayList<Company> companies=new ArrayList<Company>();
		String getAllCompanysSql="SELECT * FROM company;";
		jdbcTemplate.query(getAllCompanysSql, new RowCallbackHandler() {
			
			public void processRow(ResultSet rs) throws SQLException {
				Company company=new Company();
				company.setId(rs.getInt("company_id"));
				company.setName(rs.getString("company_name"));
				companies.add(company);
			}
		});
		if(companies.isEmpty()){
			return null;
		}else{
			return companies;
		}
	}
}
